package com.itcast.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itcast.reggie.mapper.DishDao;
import com.itcast.reggie.pojo.Dish;
import com.itcast.reggie.Dto.DishDto;
import com.itcast.reggie.pojo.DishFlavor;
import com.itcast.reggie.service.DishFlavorService;
import com.itcast.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService{
    @Autowired
   private DishFlavorService dishFlavorService;

    //添加新菜品的方法
    //这个方法是向dish 和 dishFlavor 表里面添加数据 同时操作了两个表,所以要添加事务管理
    @Override
    @Transactional
    public void saveWithFlavor(DishDto dishDto) {
        //this 指的是本类
        this.save(dishDto);
        saveFlavors(dishDto);
    }

    //修改
    @Override
    public void updateWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);
        //flavor 里面的数据有可能会增加,减少,修改
        //先把flavor 里面旧的数据全删了
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("dish_id",dishDto.getId());
        dishFlavorService.remove(wrapper);
        //再把新的加进去
        saveFlavors(dishDto);
    }

    //修改起售停售状态
    @Override
    public void updateStatus(int statu, Long[] ids) {
        for (Long id : ids) {
            Dish dish = this.getById(id);
            dish.setStatus(statu);
            QueryWrapper<Dish> wrapper = new QueryWrapper<>();
            wrapper.eq("id",id);
            this.update(dish,wrapper);
        }
    }

    //菜品批量删除
    @Override
    public void deleteByIds(Long[] ids) {
        QueryWrapper<Dish> wrapper = new QueryWrapper<>();
        wrapper.in("id",ids);
        this.remove(wrapper);
    }


    //将多个口味加入到dish_flavor表里的方法
    private void saveFlavors(DishDto dishDto) {
        List<DishFlavor> flavors = dishDto.getFlavors();
        //遍历flavor,赋给id值.
        for (DishFlavor flavor : flavors) {
            flavor.setDishId(dishDto.getId());
        }
        //saveBatch 添加多个
        dishFlavorService.saveBatch(flavors);
    }
}
